<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Episode;
use App\Models\History;
use App\Models\Like;
use App\Models\Share;
use App\Models\Video;
use Illuminate\Http\Request;

class ShareController extends Controller
{
    /***
     *我的喜欢列表
     * @param Request $request
     * @param Episode $episode
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request, Like $like)
    {
        $ep = $this->user->like()->orderByDesc('created_at')->paginate(10);
        if ($ep->isEmpty()) {
            return $this->error('没有喜欢记录');
        }
        $ep = $ep->toArray();
        foreach ($ep['data'] as &$item) {
            $item['cover'] = dealUrl($item['cover']);
            $uplist = Video::where('episodes_id', $item['id'])->max('sort');
            $item['uplist'] = empty($uplist) ? 0 : $uplist;
            $video_id = History::where('user_id', $this->user->id)->where('traces_id', $item['id'])->value('video_id');
            $looking = Video::where('id', $video_id)->value('sort');
            $item['looking'] = empty($looking) ? 0 : $looking;
        }
        return $this->success('success', $ep);
    }


    /***
     * 添加分享
     * @param Request $request
     * @param Episode $episode
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request, Share $share)
    {
        if (empty($this->user)) {
            return $this->error('未登录');
        }
        if ($request->has('video_id') && isset($request->video_id)) {
            $ep = Video::find($request->video_id);
            if (empty($ep)) {
                return $this->error('该视频不存在');
            }
            $data = [
                'user_id' => $this->user->id,
                'video_id' => $request->video_id,
            ];
        } else {
            $data = [
                'user_id' => $this->user->id
            ];
        }
        $is_cun = $share->updateOrCreate($data, $data);
        return $this->success('分享成功', $is_cun);
    }

    /***
     * 删除喜欢
     * @param Like $like
     * @return \Illuminate\Http\JsonResponse
     */
    public function rezuiju(Like $like)
    {
//            $ret=$like->where('user_id',$this->user->id)->delete();//软删除
        $ret = $like->where('user_id', $this->user->id)->forceDelete();//软删除
//        $ret=$like->where('user_id',$this->user->id)->restore();//恢复软删除
        if ($ret) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
}
